package com.ajx.core.app;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lai on 2017/11/28.
 */

public class Configurator {
    private static final Map<ConfigKeys, Object> CONFIGS = new HashMap<>();

    private static final ArrayList<String> dirs=new ArrayList<>();
    public <T> T getConfiguration(ConfigKeys key) {
        checkReady();
        return (T) CONFIGS.get(key);
    }

    private Configurator() {

        CONFIGS.put(ConfigKeys.READY, false);
    }

    private static final class Holder {
        private static final Configurator INSTANCE = new Configurator();
    }

    static Configurator getInstance() {
        return Holder.INSTANCE;
    }

    Configurator withContext(Context context) {
        CONFIGS.put(ConfigKeys.CONTEXT, context);
        return this;
    }

    public Configurator withDir(String path){
        dirs.add(path);
        return this;
    }
    public Configurator withApiHost(String path){
        CONFIGS.put(ConfigKeys.API_HOST,path);
        return this;
    }

    public Configurator withSpName(String spName){
        CONFIGS.put(ConfigKeys.SP_NAME,spName);
        return this;
    }


    public void configure() {
        Handler handler = new Handler();
        CONFIGS.put(ConfigKeys.BACKGROUND_HANDLER, handler);
        CONFIGS.put(ConfigKeys.READY, true);
        Utils.init((Application) Cube.getApplication());
        init();
    }

    /**
     * 在程序开始时要做的事都放这里
     */
    private void init() {
        if (!dirs.isEmpty()){
            for (String s:dirs){
                FileUtils.createOrExistsDir(s);
            }
        }
    }

    public Map<ConfigKeys, Object> getConfigs() {
        checkReady();
        return CONFIGS;
    }




    public void checkReady() {
        boolean isReady = (boolean) CONFIGS.get(ConfigKeys.READY);
        if (!isReady) {
            throw new RuntimeException("configuration not ready ,call configure() to init");
        }
    }


}
